package com.hp.gxw.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hp.gxw.cache.CommonCache;
import com.hp.gxw.constant.BaseEntry;
import com.hp.gxw.constant.LayTableR;
import com.hp.gxw.constant.R;
import com.hp.gxw.entity.BaseCommonDataDictionaryAndSet;
import com.hp.gxw.entity.CostEquipment;
import com.hp.gxw.entity.CostEquipmentUsagerate;
import com.hp.gxw.service.ICostEquipmentService;
import com.hp.gxw.service.ICostEquipmentUsagerateService;
import com.hp.gxw.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huangping
 * @since 2024-01-04
 */
@Controller
@RequestMapping("/manage/equipment_usagerate")
public class CostEquipmentUsagerateController extends CommonController{

    @Autowired
    private ICostEquipmentUsagerateService iCostEquipmentUsagerateService;

    @Autowired
    private ICostEquipmentService iCostEquipmentService;

    @Autowired
    private  CommonCache commonCache;

    @RequestMapping("/list/{happenMonth}")
    @ResponseBody
    public LayTableR list(@PathVariable("happenMonth") String happenMonth, Integer page, Integer limit, String master) throws Exception {
        QueryWrapper<Object> ew = ConditionUtil.convert(master, new QueryWrapper<>());
        ew.eq("happen_month", happenMonth);
        BaseEntry baseEntry = commonCache.init("cost_equipment_usagerate");
        IService<Object> iService = baseEntry.getIService();
        Page<Object> pageList = iService.page(new Page<>(page, limit), ew);
        List<BaseCommonDataDictionaryAndSet> collect = baseEntry.getSetList().stream().filter(e -> e.getQueryConstantId() != null).collect(Collectors.toList());
        List<Map> resultList = dataTransfer(pageList.getRecords(), collect);
        return LayTableR.result(0, pageList.getTotal(), resultList);
    }

    @RequestMapping("/download_templet")
    @ResponseBody
    public void templet(HttpServletResponse response) {
        try {
            //excel表头
            List<TitleEntity> titleList=new ArrayList<>();
            titleList.add(new TitleEntity("0",null,"设备使用率导入模板",null));
            titleList.add(new TitleEntity("01","0","设备编码",null));
            titleList.add(new TitleEntity("02","0","使用率(%)",null));
            titleList.add(new TitleEntity("03","0","发生月(格式：年-月)",null));
            List<CostEquipmentUsagerate> list = new ArrayList<>();
            ExcelTool excelTool = new ExcelTool("设备使用率导入模板",20,20);
            List<Column>  titleData = excelTool.columnTransformer(titleList,"t_id","t_pid","t_content","t_fielName","0");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("设备使用率导入模板.xlsx", "utf-8"));
            excelTool.exportExcel(titleData,list, response.getOutputStream(),true,true);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设备使用率导入
     * @param data
     * @return
     */
    @RequestMapping("/upload/{type}")
    @ResponseBody
    public R upload(String data, @PathVariable("type") String type) {
        String msg = "";
        try {
            List<CostEquipmentUsagerate> list = JSON.parseArray(data, CostEquipmentUsagerate.class);
            int rowNum = 1;
            String happenMonth = null;
            for (CostEquipmentUsagerate costEquipmentUsagerate : list) {
                /**为空判断*/
                if(StringUtils.isEmpty(costEquipmentUsagerate.getEquipmentName()) || costEquipmentUsagerate.getUsageRate() == null || StringUtils.isEmpty(costEquipmentUsagerate.getHappenMonth())) {
                    if (StringUtils.isEmpty(costEquipmentUsagerate.getEquipmentName())) {
                        msg += "第" + rowNum + "行数据,设备为空<br/>";
                    }
                    if (costEquipmentUsagerate.getUsageRate() == null) {
                        msg += "第" + rowNum + "行数据,设备使用率为空<br/>";
                    }
                    if (StringUtils.isEmpty(costEquipmentUsagerate.getHappenMonth())) {
                        msg += "第" + rowNum + "行数据,发生月为空<br/>";
                    }
                }
                /**验证发生月格式是否正确*/
                if(costEquipmentUsagerate.getHappenMonth().length() != 7){
                    msg += "第" + rowNum + "行数据,发生月格式不为年-月(eg:2024-01)<br/>";
                }else if(!costEquipmentUsagerate.getHappenMonth().substring(4,5).equals("-")){
                    msg += "第" + rowNum + "行数据,发生月格式不为年-月(eg:2024-01)<br/>";
                }
                /**验证发生月是否存在多个月份*/
                if(happenMonth == null){
                    happenMonth = costEquipmentUsagerate.getHappenMonth();
                }else{
                    if(!happenMonth.equals(costEquipmentUsagerate.getHappenMonth())){
                        msg += "第" + rowNum + "行数据,发生月与前面的数据不在同一个月<br/>";
                    }
                }
                CostEquipment equipment = iCostEquipmentService.getOne(new LambdaQueryWrapper<CostEquipment>().eq(CostEquipment::getCode, costEquipmentUsagerate.getEquipmentName()));
                if(equipment == null) {
                    msg += "第" + rowNum + "行数据,设备："+costEquipmentUsagerate.getEquipmentName()+"不存在!<br/>";
                }else {
                    costEquipmentUsagerate.setEquipmentId(equipment.getId());
                }
                costEquipmentUsagerate.setCreateUser(ShiroUtil.getUserId());
                costEquipmentUsagerate.setCreateTime(new Date());
                rowNum++;
            }
            Map<String, List<CostEquipmentUsagerate>> collect = list.stream().collect(groupingBy(CostEquipmentUsagerate::getEquipmentName));
            Set<Map.Entry<String, List<CostEquipmentUsagerate>>> entries = collect.entrySet();
            for (Map.Entry<String, List<CostEquipmentUsagerate>> entry : entries) {
                if(entry.getValue().size() > 1){
                    msg += "设备："+entry.getKey()+"存在多条数据!<br/>";
                }
            }
            if(StringUtils.isNotEmpty(msg)) {
               return R.error(msg);
            }
            if(list.size() > 0){
                switch (type){
                    case "cover":
                        iCostEquipmentUsagerateService.coverUpload(list);
                        break;
                    case "difference":
                        Iterator<CostEquipmentUsagerate> iterator = list.iterator();
                        while (iterator.hasNext()){
                            CostEquipmentUsagerate equipmentUsagerate = iterator.next();
                            CostEquipmentUsagerate usagerate = iCostEquipmentUsagerateService.getOne(new LambdaQueryWrapper<CostEquipmentUsagerate>()
                                    .eq(CostEquipmentUsagerate::getEquipmentId, equipmentUsagerate.getEquipmentId())
                                    .eq(CostEquipmentUsagerate::getHappenMonth, equipmentUsagerate.getHappenMonth()));
                            if(usagerate != null){
                                iterator.remove();
                            }
                        }
                        if(list.size() > 0){
                            iCostEquipmentUsagerateService.saveBatch(list);
                        }
                        break;
                }
            }
        }catch (NumberFormatException ne) {
            ne.printStackTrace();
            return R.error("使用率只能是数字！");
        }catch (Exception e) {
            e.printStackTrace();
            return R.error("系统异常");
        }
        return R.ok();
    }
}

